﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TPCN.DAL;
using TPCN.Common;
using TPCN.Commons;

namespace TPCN.Admincp
{
    public partial class Menu : System.Web.UI.Page
    {

        private static string MenuID = String.Empty;
        private static string old_parentID = String.Empty;
        private static List<MenuObj> source;
        private static MenuObj obj;

        private const string UPDATE = "Cập nhật";
        private const string INSERT = "Thêm";
        private const string CMD_EDIT = "cmdEdit";
        private const string CMD_DELETE = "cmdDelete";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGridView();
                GetCategoryToDropdownList();
                GetMenuToDropdownList("0");
                InitForm();
            }
        }

        private void InitForm()
        {
            EditFormPanel.Visible = false;
            GridViewPanel.Visible = true;
            ButtonPanel.Visible = true;
        }

        private void BindGridView()
        {
            source = new List<MenuObj>();
            source = MenuDAL.GetByAll();
            MenuGridView.DataSource = source;
            MenuGridView.DataBind();
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            TurnPanelOnOff();
            btnSave.Text = INSERT;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < MenuGridView.Rows.Count; i++)
            {
                GridViewRow row = MenuGridView.Rows[i];
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkSelect");
                    if (chk.Checked)
                    {
                        string ID = row.Cells[1].Text;
                        MenuDAL.Delete(ID);
                    }
                }
            }
            MenuGridView.PageIndex = 0;
            BindGridView();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (isAllow(cboParentMenu.SelectedValue, cboPosition.SelectedValue))
                {
                    switch (btnSave.Text)
                    {
                        case UPDATE:
                            SetValueFromForm(false);
                            MenuDAL.Update(obj);
                            BindGridView();
                            break;
                        case INSERT:
                            SetValueFromForm(true);
                            MenuDAL.Insert(obj);
                            BindGridView();
                            break;
                    }
                    Reset();
                    TurnPanelOnOff();
                    obj = null;
                    old_parentID = String.Empty;
                    ErrorPanel.Visible = false;
                }
                else
                {
                    lblMessage.Text = "Menu \"" + cboParentMenu.SelectedItem + "\" chứa vượt quá số lượng cho phép. Vui lòng chọn menu khác!";
                    ErrorPanel.Visible = true;
                    cboParentMenu.Focus();
                }
            }
        }

        private void Reset()
        {
            ControlHelper.ResetControl(EditFormPanel);
            type_1.Attributes.CssStyle["display"] = "block";
            type_2.Attributes.CssStyle["display"] = "none";
            type_3.Attributes.CssStyle["display"] = "none";
            lblContent.InnerHtml = "Danh mục";
            cboParentMenu.Items.Clear();
            cboParentMenu.Items.Add(new ListItem("----- Vui lòng chọn vị trí trước -----", "-1"));
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            TurnPanelOnOff();
            ErrorPanel.Visible = false;
            Reset();
        }

        protected void DanmucGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            MenuGridView.PageIndex = e.NewPageIndex;
            BindGridView();
        }

        protected void MenuGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            MenuID = e.CommandArgument.ToString();
            obj = new MenuObj();
            obj = MenuDAL.GetByID(MenuID);
            switch (e.CommandName)
            {
                case CMD_EDIT:
                    FillValueToForm(obj);
                    btnSave.Text = UPDATE;
                    TurnPanelOnOff();
                    break;
                case CMD_DELETE:
                    MenuDAL.Delete(obj.MenuID);
                    BindGridView();
                    break;
            }
        }

        private void TurnPanelOnOff()
        {
            GridViewPanel.Visible = !GridViewPanel.Visible;
            EditFormPanel.Visible = !EditFormPanel.Visible;
            ButtonPanel.Visible = !ButtonPanel.Visible;
        }

        private void FillValueToForm(MenuObj obj)
        {
            txtName.Text = obj.Name;
            txtTitle.Text = obj.Title;
            txtKeyword.Text = obj.Keyword;
            txtDescription.Text = obj.Description;
            txtThutu.Text = obj.Order;
            cboPosition.SelectedValue = obj.Position;
            GetMenuToDropdownList(obj.Position);
            cboTarget.SelectedValue = obj.Target;
            cboType.SelectedValue = obj.Type;
            cboParentMenu.SelectedValue = obj.ParentID;
            chkActive.Checked = Boolean.Parse(obj.Active);
            if (obj.Type == "1")
            {
                cboCategory.SelectedValue = getCategoryIDFromUrl(obj.Link);
                type_1.Attributes.CssStyle["display"] = "block";
                type_2.Attributes.CssStyle["display"] = "none";
                type_3.Attributes.CssStyle["display"] = "none";
                lblContent.InnerHtml = "Danh mục";
            }
            else if (obj.Type == "2")
            {
                txtLink.Text = obj.Link;
                type_1.Attributes.CssStyle["display"] = "none";
                type_2.Attributes.CssStyle["display"] = "block";
                type_3.Attributes.CssStyle["display"] = "none";
                lblContent.InnerHtml = "Link";
            }
            else
            {
                txtContent.Content = obj.Content;
                type_1.Attributes.CssStyle["display"] = "none";
                type_2.Attributes.CssStyle["display"] = "none";
                type_3.Attributes.CssStyle["display"] = "block";
                lblContent.InnerHtml = "Nội dung";
            }
            old_parentID = obj.ParentID;
        }

        protected void SetValueFromForm(bool isInsert)
        {
            if (obj == null)
                obj = new MenuObj();
            obj.Name = txtName.Text;
            obj.Title = txtTitle.Text;
            obj.Order = txtThutu.Text;
            obj.Position = cboPosition.SelectedValue;
            obj.ParentID = cboParentMenu.SelectedValue;
            obj.Keyword = txtKeyword.Text;
            obj.Description = txtDescription.Text;
            obj.Type = cboType.SelectedValue;
            obj.Target = cboTarget.SelectedValue;
            if (obj.Type == "1")
                obj.Link = "~/Default.aspx?CateID=" + cboCategory.SelectedValue;
            else if (obj.Type == "2")
                obj.Link = txtLink.Text;
            else
            {
                if (isInsert)
                    obj.Link = "~/Page.aspx?id=" + MenuDAL.GetMenuID();
                else
                    obj.Link = "~/Page.aspx?id=" + obj.MenuID;
                obj.Content = txtContent.Content;
            }
            obj.Active = Convert.ToString(chkActive.Checked);
            obj.Url = StringHelper.NameToUrl(obj.Name);
        }

        protected void GetCategoryToDropdownList()
        {
            List<DanhmucObj> list = new List<DanhmucObj>();
            list = DanhmucDAL.GetByAll();
            cboCategory.DataSource = list;
            cboCategory.DataValueField = "DanhmucID";
            cboCategory.DataTextField = "Tendanhmuc";
            cboCategory.DataBind();
        }

        protected void GetMenuToDropdownList(string position)
        {
            cboParentMenu.Items.Clear();
            if (position != "0")
            {
                List<MenuObj> list = new List<MenuObj>();
                list = MenuDAL.GetRootMenu(position);
                cboParentMenu.Items.Add(new ListItem("Thanh menu chính", "0"));
                for (int i = 0; i < list.Count; i++)
                {
                    cboParentMenu.Items.Add(new ListItem("---- " + list[i].Name, list[i].MenuID));
                }
            }
            else
                cboParentMenu.Items.Add(new ListItem("----- Vui lòng chọn vị trí trước -----", "-1"));
        }

        protected string getCategoryIDFromUrl(string url)
        {
            string id = String.Empty;
            id = url.Replace("~/Default.aspx?CateID=", String.Empty);
            return id;
        }

        protected bool isAllow(string ParentID, string Position)
        {
            int count = MenuDAL.GetNumberOfChildMenu(ParentID, Position);
            if (old_parentID != ParentID && Position == "2")
            {
                if (ParentID == "0" && count == 2)
                    return false;
                else if (count == 6)
                    return false;
            }
            return true;
        }

        protected string BindType(Object obj)
        {
            string result = String.Empty;
            int type = Convert.ToInt32(obj);
            if (type == 1)
                result = "Liên kết đến danh mục";
            else if (type == 2)
                result = "Liên kết đến địa chỉ ngoài";
            else
                result = "Trang nội dung";
            return result;
        }

        protected string BindPosition(Object obj)
        {
            string result = String.Empty;
            int position = Convert.ToInt32(obj);
            if (position == 1)
                result = "Thanh menu trên";
            else
                result = "Thanh thông tin bên dưới";
            return result;
        }

        protected void cboPosition_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetMenuToDropdownList(cboPosition.SelectedValue);
        }
    }
}